using Catalog.Application.Categorys.Commands;
using Catalog.Application.Categorys.Queries;
using Catalog.Application.Contracts.DTOs;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Catalog.HttpAPI.Host.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class CategoryController : ControllerBase
    {
        private readonly IMediator _mediator;

        public CategoryController(IMediator mediator)
        {
            _mediator = mediator;

        }

        [AllowAnonymous]
        [HttpGet("{id}")]
        public async Task<ActionResult<CategoryProfileDto>> GetByIdAsync([FromQuery] GetCategoryByIdQuery query)
        {
            var category = await _mediator.Send(query);
            if (category == null)
            {
                return NotFound();
            }
            return Ok(category);
        }

        [AllowAnonymous]
        [HttpGet("search")]
        public async Task<ActionResult<List<CategoryProfileDto>>> GetListAsync([FromQuery] SearchCategoryQuery query)
        {
            var categorys = await _mediator.Send(query);
            if (categorys == null || !categorys.Any())
            {
                return NotFound("No category items found");
            }
            return Ok(categorys);
        }

        [Authorize(Roles="Admin")]
        [HttpPost("create")]
        public async Task<IActionResult> CreateAsync([FromBody] CreateCategoryCommand command)
        {

            var result = await _mediator.Send(command);

            return Ok(result);
        }

        [Authorize(Roles="Admin")]
        [HttpPut("update")]
        public async Task<ActionResult> UpdateAsync([FromBody] UpdateCategoryCommand command)
        {
            var result = await _mediator.Send(command);

            return Ok(result);
        }

        [Authorize(Roles="Admin")]
        [HttpDelete("delete/{id}")]
        public async Task<IActionResult> DeleteAsync([FromRoute] Guid id)
        {
            var command = new DeleteCategoryCommand(id);
            var result = await _mediator.Send(command);
            return Ok(result);
        }

        [Authorize(Roles="Admin")]
        [HttpPatch("change-name")]
        public async Task<IActionResult> ChangeNameAsync([FromBody] ChangeCategoryNameCommand command)
        {
            var result = await _mediator.Send(command);
            return Ok(result);
        }

        [Authorize(Roles="Admin")]
        [HttpPatch("change-description")]
        public async Task<IActionResult> ChangeDescriptionAsync([FromBody] ChangeCategoryDescriptionCommand command)
        {
            var result = await _mediator.Send(command);
            return Ok(result);
        }
    }
}